package com.zlsy.thread.atomic;

import java.util.concurrent.atomic.AtomicIntegerArray;

/**
 * @author zhouliang
 * @date 2020/8/11 19:40
 */
public class AtomicIntegerArrayDemo {
    public static void main(String[] args) {
        AtomicIntegerArray atomicIntegerArray = new AtomicIntegerArray(1000);

        Decrement decrement = new Decrement(atomicIntegerArray);
        Increment increment = new Increment(atomicIntegerArray);

        Thread[] threadsDecrement = new Thread[100];
        Thread[] threadsIncrement = new Thread[100];
        for (int i = 0; i < 100; i++) {
            threadsDecrement[i] = new Thread(decrement);
            threadsIncrement[i] = new Thread(increment);
            threadsDecrement[i].start();
            threadsIncrement[i].start();
        }

        for (int i = 0; i < 100; i++) {
            try {
                threadsDecrement[i].join();
                threadsIncrement[i].join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        for (int i = 0; i < atomicIntegerArray.length(); i++) {
            if (atomicIntegerArray.get(i) != 0) {
                System.err.println("发现了非0值");
            }
        }

        System.out.println("运行结束！");
    }
}

class Decrement implements Runnable {

    private AtomicIntegerArray atomicIntegerArray;

    public Decrement(AtomicIntegerArray atomicIntegerArray) {
        this.atomicIntegerArray = atomicIntegerArray;
    }

    @Override
    public void run() {
        for (int i = 0; i < atomicIntegerArray.length(); i++) {
            atomicIntegerArray.getAndDecrement(i);
        }
    }
}

class Increment implements Runnable {

    private AtomicIntegerArray atomicIntegerArray;

    public Increment(AtomicIntegerArray atomicIntegerArray) {
        this.atomicIntegerArray = atomicIntegerArray;
    }

    @Override
    public void run() {
        for (int i = 0; i < atomicIntegerArray.length(); i++) {
            atomicIntegerArray.getAndIncrement(i);
        }
    }
}
